﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using Org.BouncyCastle.Asn1.X509.Qualified;
using System.Text.Json;
using System.Threading.Tasks;

namespace hpcpdi
{

    /// <summary>
    /// 自定义异常中间件
    /// </summary>
    public class CustomerExceptionMiddleware
    {
        /// <summary>
        /// 委托
        /// </summary>
        private readonly RequestDelegate _next;
        public CustomerExceptionMiddleware(RequestDelegate next) {
            _next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (System.Exception ex)
            {
                context.Response.ContentType = "application/json";
                var title = "An error occured: " + ex.Message;
                var details = ex.ToString();
                var problem = new ProblemDetails {
                    Status = 500,
                    Title = title,
                    Detail = details
                };
                var stream = context.Response.Body;
                await JsonSerializer.SerializeAsync(stream, problem);
            }
        }
    }
    /// <summary>
    /// 静态类
    /// </summary>
    public static class ExceptionMiddleewareExtension {
        /// <summary>
        /// 静态方法
        /// </summary>
        /// <param name="app">要进行扩展的类型</param>
        public static void UseExceptionMiddleware(this IApplicationBuilder app) { 
        app.UseMiddleware(typeof(CustomerExceptionMiddleware));
        }
    }

}
